package com.haois.mp.database.module.wxserver.service;

import com.google.gson.Gson;
import com.haois.mp.database.module.common.daomain.TempData;
import com.haois.mp.database.module.common.daomain.TempMessage;
import com.haois.mp.database.module.wxserver.dao.BaseMessageMapper;
import com.haois.mp.database.util.jx.DateUtil;
import com.haois.mp.database.util.jx.GsonUtil;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * Created by RuiHaoZ on 2017/12/7.
 */
@Service
public class BaseMessageService {
    Logger logger = LoggerFactory.getLogger(BaseMessageService.class);
    @Autowired
    private BaseMessageMapper baseMessageMapper;
    Gson gson = new Gson();


    public void saveInMsg(WxMpXmlMessage wxMpXmlMessage) {
        try {
            baseMessageMapper.saveInMsg(wxMpXmlMessage, gson.toJson(wxMpXmlMessage));
        } catch (Exception e) {
            logger.error("保存收到的用户消息出错：【{}】", gson.toJson(wxMpXmlMessage));
        }
    }

    public void saveOutMsg(WxMpXmlOutMessage wxMpXmlMessage, long msgId) {
        try {
            baseMessageMapper.saveOutMsg(wxMpXmlMessage, gson.toJson(wxMpXmlMessage), msgId);
        } catch (Exception e) {
            logger.error("保存发送给用户的消息出错：【{}】", gson.toJson(wxMpXmlMessage));
        }
    }

    public String save(WxMpTemplateMessage tm, TempMessage tempMessage, String reply) {
        TempMessage tme = new TempMessage();
        BeanUtils.copyProperties(tempMessage, tme);
        TempData tempData0 = new TempData();

        tempData0.setTime(DateUtil.getYMdHms());
        tempData0.setContent(tm.toJson());
        tempData0.setRemark(reply);
        tempData0.setReceiver((String) tme.getMapData().get("receiver"));
        tempData0.setSender((String) tme.getMapData().get("sender"));
        tme.setTempData(tempData0);
        baseMessageMapper.addMsgRecord(tme);
        return tme.getTempData().getId();
    }

    public void save(Map mapData, String id, String type) {
        TempData tempData = new TempData(mapData);
        try {
            tempData.setTime(DateUtil.getYMdHms());
            baseMessageMapper.saveTempInfo(tempData, id, type);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("保存信息出错: {}", e.getMessage());
            logger.error("信息内容为: {}", GsonUtil.toJson(tempData));
        }

    }

    public Map<String, Object> getTempInfo(String id) {
        return baseMessageMapper.getTempInfo(id);
    }

}
